package com.frank.javaBeanValidation.web;

import com.frank.javaBeanValidation.entity.Book;
import com.frank.javaBeanValidation.entity.Insert;
import com.frank.javaBeanValidation.entity.Student;
import com.frank.javaBeanValidation.entity.Update;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Max;

/**
 * @author 小石潭记
 * @date 2020/10/22 11:00
 * @Description: ${todo}
 */
@RestController
@RequestMapping("/javaBean")
@Slf4j
@Validated
public class JavaBeanController {

    /**
     * 添加Book对象
     * @param book
     */
    @PostMapping("/book")
    public Book addBook(@RequestBody @Valid Book book) {
        log.info("保存的图书信息,{}", book);
        return book;
    }

    @GetMapping("/get")
    public Book addBook() {
        Book book = new Book();
        book.setBookIsbn("isg11212");
        book.setBookName("笑傲江湖");
        return book;
    }

    /**
     * 这里的max需要在controller上面添加@Validated注解才会生效
     * @param id
     * @return
     */
    @GetMapping("/index")
    public Book index(@Max(value = 50, message="最大值为50") int id) {
        Book book = new Book();
        book.setId(id);
        book.setBookIsbn("index");
        book.setBookName("艾欧尼亚");
        return book;
    }

    @GetMapping("/add")
    public String addStudent(@Validated(Insert.class) Student student, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            if(bindingResult.hasErrors()){
                for (ObjectError error: bindingResult.getAllErrors()) {
                    log.error(error.getDefaultMessage());
                    return error.getDefaultMessage();
                }
            }
        }
        return "add";
    }

    /**
     * 因为更新的时候必须需要id，而添加的时候往往不需要id，所以通过分组来进行区分
     * @param student
     * @return
     */
    @GetMapping("/update")
    public String update(@Validated(Update.class) Student student){
        return "update ok";
    }

    @PostMapping("/edit")
    public String edit(@Validated @RequestBody Student student){
        return "edit ok";
    }


}
